package com.ilop.sthome.ui.activity.detail;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.example.common.base.BaseActivity;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SendAutoCommand;
import com.ilop.sthome.common.command.SendDeviceCommand;
import com.ilop.sthome.data.enums.SmartDevice;
import com.ilop.sthome.data.event.EventAnswerOK;
import com.ilop.sthome.data.event.EventRefreshDevice;
import com.ilop.sthome.data.greenDao.AutomationBean;
import com.ilop.sthome.data.greenDao.DefaultBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.ui.activity.detail.common.CommonFunctionActivity;
import com.ilop.sthome.ui.activity.detail.common.ModeSwitchActivity;
import com.ilop.sthome.ui.activity.detail.socket.LinkageListActivity;
import com.ilop.sthome.ui.activity.detail.socket.TimingListActivity;
import com.ilop.sthome.ui.activity.device.DeviceDetailActivity;
import com.ilop.sthome.ui.activity.device.DeviceHistoryActivity;
import com.ilop.sthome.ui.activity.device.DeviceSettingActivity;
import com.ilop.sthome.ui.activity.device.GatewayMainActivity;
import com.ilop.sthome.ui.activity.main.MainActivity;
import com.ilop.sthome.utils.CoderUtils;
import com.ilop.sthome.utils.greenDao.utils.AutomationDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.DefaultDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.utils.tools.ByteUtil;
import com.siterwell.familywellplus.R;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author skygge
 * @date 2019-12-10.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：详情页BASE类
 */
public class BaseDetailActivity<B extends ViewDataBinding> extends BaseActivity{

    protected B mDBind;

    private String mAutoCode;
    protected String mDeviceName;
    protected int mDeviceId;
    private int mEntrance = -1;

    protected SmartDevice smartDevice;
    protected DeviceInfoBean mDevice;
    protected SendDeviceCommand mSendEquipment;

    private DefaultBean mDefault;
    private AutomationBean mAutomation;
    private SendAutoCommand mSendAuto;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        mDBind = DataBindingUtil.setContentView(this, getLayoutId());
        initialization();
    }

    /**
     * 初始化
     */
    @Override
    protected void initialize() {
        mDeviceName = getIntent().getStringExtra(CommonId.KEY_DEVICE_NAME);
        mDeviceId = getIntent().getIntExtra(CommonId.KEY_DEVICE_ID,-1);
        mEntrance = getIntent().getIntExtra(CommonId.KEY_DEVICE_TYPE,-1);
        mDevice = DeviceDaoUtil.getInstance().findByDeviceId(mDeviceName, mDeviceId);
        if(mDevice == null){
            showToast(getString(R.string.device_not_exist));
            finish();
            return;
        }
        smartDevice = SmartDevice.getType(mDevice.getDevice_type());
        DeviceInfoBean deviceInfoBean = DeviceDaoUtil.getInstance().findGatewayByDeviceName(mDeviceName);
        if (deviceInfoBean == null){
            showToast(getString(R.string.please_add_gateway_first));
            finish();
            return;
        }
        mSendEquipment = new SendDeviceCommand(this, deviceInfoBean);
        mSendAuto = new SendAutoCommand(mContext, deviceInfoBean);
    }

    @Override
    protected void initDataBus() {
        LiveDataBus.get().with(CommonId.DEFAULT_SCENE_CLICK, DefaultBean.class).observe(this, defaultBean -> {
            if (defaultBean!=null) {
                switch (smartDevice) {
                    case EE_DEV_SOCKET:
                    case EE_DEV_LIGHTING_MODULE:
                    case EE_DEV_MANIPULATOR:
                    case EE_DEV_SOLENOID_VALVE:
                        defaultItemClick(defaultBean.getRecommendId());
                        break;
                    case EE_DEV_FLASH_ALARM:
                        if ("27".equals(defaultBean.getRecommendId())) {
                            intentToCommon(defaultBean);
                        } else if ("28".equals(defaultBean.getRecommendId())) {
                            intentToTimeOrLinkage(false, "28");
                        }
                        break;
                    default:
                        intentToCommon(defaultBean);
                        break;
                }
            }
        });

        LiveDataBus.get().with(CommonId.COMMON_FUNCTION_CLICK, DefaultBean.class).observe(this, defaultBean -> {
            assert defaultBean != null;
            mDefault = defaultBean;
            mAutomation = AutomationDaoUtil.getInstance().findAutomationByRecommendId(mDefault);
            if (mAutomation == null){
                int hasDevice = DefaultDaoUtil.getInstance().findDefaultHasType(defaultBean);
                if (hasDevice != -1) {
                    String finalCode = CoderUtils.getNewCode(defaultBean);
                    String finalCRC = ByteUtil.stringToCRC(finalCode);
                    mAutoCode = finalCode + finalCRC;
                    String mDefaultCode = "FFFF" + mAutoCode;
                    mSendAuto.increaseAutomation(mDefaultCode.toUpperCase());
                    showProgressDialog();
                }else {
                    showToast(getString(R.string.lack_of_equipment));
                }
            }else {
                mSendAuto.deleteAutomation(mAutomation.getMid());
            }
        });

        LiveDataBus.get().with(CommonId.DEFAULT_SCENE_CHANGE, DefaultBean.class).observe(this, defaultBean -> {
            assert defaultBean != null;
            Intent intent = new Intent(mContext, ModeSwitchActivity.class);
            intent.putExtra(CommonId.KEY_RECOMMEND_ID, defaultBean.getId());
            intent.putExtra(CommonId.KEY_DEVICE_NAME, mDevice.getDeviceName());
            mContext.startActivity(intent);
        });

        LiveDataBus.get().with(CommonId.KEY_EVENT_REFRESH_DEVICE, EventRefreshDevice.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "onEventMainThread: subDevice " +  event.getDevice_status());
                int deviceId = event.getDevice_id();
                String deviceStatus = event.getDevice_status();
                String deviceType = event.getDevice_type();
                String deviceName = event.getDeviceName();
                if (deviceName.equals(mDevice.getDeviceName()) && deviceId == mDevice.getDevice_ID() && deviceType.equals(mDevice.getDevice_type())) {
                    mDevice.setDevice_status(deviceStatus);
                    refreshUI(deviceStatus);
                }
            }
        });

        LiveDataBus.get().with(CommonId.KEY_ANSWER_OK, EventAnswerOK.class).observe(this, event -> {
            if (event != null) {
                dismissProgressDialog();
                int result = CoderUtils.getAnswerResult(event.getData_str1(), event.getData_str2());
                Log.i(TAG, "initDataBus: answerOK--" + result);
                switch (result){
                    case 1:
                        showToast(getString(R.string.success_test));
                        refreshSocket();
                        break;
                    case 8:
                        String fullCode = event.getData_str2().substring(3) + mAutoCode;
                        if (fullCode.length()>16) {
                            ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
                            Runnable runnable = () -> CoderUtils.analysisFullCode(fullCode.toUpperCase(), mDeviceName);
                            mExecutorService.execute(runnable);
                            refreshDefaultList();
                        }
                        break;
                    case 10:
                        AutomationDaoUtil.getInstance().getAutomationDao().delete(mAutomation);
                        refreshDefaultList();
                        break;
                }
            }
        });
    }

    /**
     * 更新UI
     */
    protected void refreshUI(String status) {

    }

    /**
     * 更新UI
     */
    protected void refreshDefaultList() {

    }

    /**
     * 更新插座
     */
    protected void refreshSocket() {

    }

    private void defaultItemClick(String recommendId){
        switch (recommendId){
            case "18":
                intentToTimeOrLinkage(true, "18");
                break;
            case "19":
                intentToTimeOrLinkage(false, "19");
                break;
            case "29":
                intentToTimeOrLinkage(true, "29");
                break;
            case "2A":
                intentToTimeOrLinkage(false, "2A");
                break;
            case "2B":
                intentToTimeOrLinkage(true, "2B");
                break;
            case "2C":
                intentToTimeOrLinkage(false, "2C");
                break;
        }
    }

    private void intentToCommon(DefaultBean defaultBean){
        Intent intent = new Intent(mContext, CommonFunctionActivity.class);
        intent.putExtra(CommonId.KEY_RECOMMEND_ID, defaultBean.getId());
        mContext.startActivity(intent);
    }

    private void intentToTimeOrLinkage(boolean isTime, String recommendId){
        Intent intent = new Intent();
        intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
        intent.putExtra(CommonId.KEY_DEVICE_ID, mDeviceId);
        intent.putExtra(CommonId.KEY_RECOMMEND_ID, recommendId);
        intent.setClass(mContext, isTime ? TimingListActivity.class : LinkageListActivity.class);
        mContext.startActivity(intent);
    }

    public void finish(View view){
        if (mEntrance == -1){
            finish();
        }else {
            Intent intent = new Intent();
            if (mEntrance == 0) {
                intent.setClass(mContext, GatewayMainActivity.class);
            }else {
                intent.setClass(mContext, MainActivity.class);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        }
    }

    public void manager(View view){
        Intent intent = new Intent(this, DeviceSettingActivity.class);
        intent.putExtra(CommonId.KEY_DEVICE_ID, mDevice.getDevice_ID());
        intent.putExtra(CommonId.KEY_DEVICE_NAME, mDevice.getDeviceName());
        startActivity(intent);
    }

    public void history(View view){
        Intent intent = new Intent(this, DeviceHistoryActivity.class);
        intent.putExtra(CommonId.KEY_DEVICE_ID, mDevice.getDevice_ID());
        intent.putExtra(CommonId.KEY_DEVICE_NAME, mDevice.getDeviceName());
        startActivity(intent);
    }

    public void detail(View view){
        Intent intent = new Intent(this, DeviceDetailActivity.class);
        intent.putExtra(CommonId.KEY_DEVICE_ID, mDevice.getDevice_ID());
        intent.putExtra(CommonId.KEY_DEVICE_NAME, mDevice.getDeviceName());
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        if (mEntrance == -1){
            finish();
        }else {
            Intent intent = new Intent();
            if (mEntrance == 0) {
                intent.setClass(mContext, GatewayMainActivity.class);
            }else {
                intent.setClass(mContext, MainActivity.class);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        }
    }
}
